import time
from autotest.logs.logger import Logger

#模拟鼠标操作
from selenium.webdriver.common.action_chains import ActionChains
#显示等待
from selenium.webdriver.support.wait import WebDriverWait
#下拉框
from selenium.webdriver.support.select import Select
import os.path

logger=Logger(logger="BasePage").getlog()

class BasePage(object):
    #定义一个页面基类，让所有页面都继承这个类，封装一些常用的页面操作方法

    def __init__(self, driver):
        self.driver = driver
#打开连接
    def open(self,url):
        self.driver.get(url)
#退出浏览器和退出测试
    def quit_browser(self):
        self.driver.quit()
#浏览器前进
    def forward(self):
        self.driver.forward()
#浏览器后退
    def back(self):
        self.driver.back()
#浏览器等待加载，显示等待根据传的元素判断是否加载完毕
    def wait(self,loc,seconds):
        try:
            wait_ = WebDriverWait(self.driver, seconds)
            wait_.until(lambda driver:driver.find_element(*loc))
            logger.info("等待%d秒。"% seconds)
        except NameError as e:
            logger.info("元素加载失败%s" % e)
#保存截图
    def get_windows_img(self):
        file_path=os.path.dirname(os.path.abspath('.'))+'/autotest/screenshots/'
        rq=time.strftime("%Y%m%d%H%M%S",time.localtime())
        screen_name=file_path+rq+'.png'
        try:
            self.driver.get_screenshot_as_file(screen_name)
            logger.info("已经截图保存路径为：/screenshots")
        except NameError as e:
            logger.info("截图失败%s" % e)
#定位元素
    def find_element(self,loc):
        return self.driver.find_element(*loc)
#输入
    def send_keys(self,selector,text):
        el=self.find_element(selector)
        el.clear()
        try:
            el.send_keys(text)
            logger.info("输入\'%s\'内容"% text)
        except NameError as e:
            logger.info("输入时没选中元素%s" % e)
        self.get_windows_img()
#清除文本框
    def clear(self,selector):
        el=self.find_element(selector)
        try:
            el.clear()
            logger.info("内容清除成功")
        except NameError as e:
            logger.info("清除时没选中元素%s" % e)
        self.get_windows_img()
#点击元素
    def click(self,selector):
        el=self.find_element(selector)
        try:
            el.click()
            logger.info("点击")
        except NameError as e:
            logger.info("点击没选择元素%s" % e)
        self.get_windows_img()
#鼠标事件(左键点击)
    def move_element(self,loc,sloc):
        mouse=self.find_element(loc)
        try:
            ActionChains(self.driver).move_to_element(mouse).perform()
            self.click(loc)
            pass
        except Exception as e:
            logger.info("右击失败元素没拿到%s" % e)
        self.get_windows_img()
#强制等待
    def sleep(self,seconds):
        time.sleep(seconds)
        logger.info("强制等待%d秒"% seconds)